#include "stdafx.h"
#include "MsgBuilderSimple.h"
#include "MsgCategory.h"
#include "MsgFactoryNetwork.h"
//#include "MsgLogin.h"
//#include "MsgPlayer.h"

const char c_msg_header_flag = 47;
const short s_msg_header_len = 100;

MsgBuilderWithFactory::MsgBuilderWithFactory(IMsgFactory* pFact /* = NULL */)
:m_pMsgFact(pFact)
{
	if (m_pMsgFact==NULL)
	{
		m_pMsgFact = new MsgFactoryNetwork;
	}
}

bool
MsgBuilderWithFactory::onEncodeMsg(IMsg* pMsg, MsgOStream& stream)
{
	if (pMsg!=NULL)
	{
		stream << c_msg_header_flag;
		stream << pMsg->getMsgCate() << pMsg->getMsgID() << s_msg_header_len;
		return pMsg->encode(stream);
	}
	else
	{
		return false;
	}
}


bool
MsgBuilderWithFactory::onDecodeMsg(IMsg*& pMsg, MsgIStream& stream)
{
	char cFlag = 0;
	stream >> cFlag;

	//if (cType!=c_msg_header_type || cTag!=c_msg_header_tag)
	//{
	//	LOG_ERROR("Failed to decode msg, invalid message type or tag!");
	//}

	char ucMC = 0;
	short nMID = 0, nLen = 0;
	stream >> ucMC >> nMID >>nLen;


	pMsg = m_pMsgFact->createMsg(ucMC, nMID);
	if (pMsg != NULL)
	{
		return pMsg->decode(stream);
	}
	else
	{
		LOG_ERROR_V("Failed to decode msg, message cate or id %d, %d!", ucMC, nMID);
		return false;
	}
}

